/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.rukopisyimport.sourceData;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Martin Rehanek (rehan@mzk.cz)
 */
public class ManuscriptIdentifier {

    private static final Map<MarcDocument, ManuscriptIdentifier> marcIdCache = new HashMap<MarcDocument, ManuscriptIdentifier>();
    private final String base;
    private final String sysno;
    private final String barcode;

    public static ManuscriptIdentifier instanceOf(MarcDocument marc, BarCodeResolver barCodeResolver) throws Exception {
        ManuscriptIdentifier identifier = marcIdCache.get(marc);
        if (identifier == null) {
            identifier = fromMarc(marc, barCodeResolver);
            marcIdCache.put(marc, identifier);
        }
        return identifier;
    }

    private static ManuscriptIdentifier fromMarc(MarcDocument marc, BarCodeResolver barCodeResolver) throws Exception {
        return instanceOf(marc.findBase(), marc.findSysno(), barCodeResolver);
    }

    public static ManuscriptIdentifier instanceOf(String base, String sysno, BarCodeResolver barCodeResolver) throws Exception {
        String barcode = barCodeResolver.findBarcode(base, sysno);
        ManuscriptIdentifier result = new ManuscriptIdentifier(base, sysno, barcode);
        return result;
    }

    private ManuscriptIdentifier(String base, String sysno, String barcode) {
        this.base = base;
        this.sysno = sysno;
        this.barcode = barcode;
    }

    /**
     * @return the base
     */
    public String getBase() {
        return base;
    }

    /**
     * @return the sysno
     */
    public String getSysno() {
        return sysno;
    }

    /**
     * @return the barcode
     */
    public String getBarcode() {
        return barcode;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final ManuscriptIdentifier other = (ManuscriptIdentifier) obj;
        if ((this.base == null) ? (other.base != null) : !this.base.equals(other.base)) {
            return false;
        }
        if ((this.sysno == null) ? (other.sysno != null) : !this.sysno.equals(other.sysno)) {
            return false;
        }
        if ((this.barcode == null) ? (other.barcode != null) : !this.barcode.equals(other.barcode)) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + (this.base != null ? this.base.hashCode() : 0);
        hash = 53 * hash + (this.sysno != null ? this.sysno.hashCode() : 0);
        hash = 53 * hash + (this.barcode != null ? this.barcode.hashCode() : 0);
        return hash;
    }
}
